﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
//#include <QtGui/QApplication>
//#include <QtGui/QFileDialog>
//#include <QtGui/QMessageBox>
#include <QtCore/QFile>
#include <QtCore/QTextStream>
#include <QTextCodec>
#include <QtDebug>
#include <QFile>
#include <QUrl>
#include <QDesktopServices>
#include <QMessageBox>
#include <QFileDialog>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    serPort = new QSerialPort(this);
    initAndFlush();
    connect(serPort, SIGNAL(readyRead()), this, SLOT(readSerPort()));

    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(on_pushButton_2_clicked()));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::initAndFlush()
{
    ui->comboBox->addItems(getListSerPort());

    QFile file(":/text/LICENSE");
    if(!file.open(QFile::ReadOnly | QFile::Text)){
        qDebug() << "error open LICENSE";
    }
    QTextStream in(&file);
    QString aboutText = in.readAll();
//    qDebug() << aboutText;
    ui->textEdit_7->setPlainText(aboutText);
    file.close();


}



QList<QString> MainWindow::getListSerPort()
{
    QSerialPortInfo portInfo;
    QList<QSerialPortInfo> listPortInfo = portInfo.availablePorts();
    QList<QString> listComName;
    for(int i=0;i<listPortInfo.length();i++){
        listComName.append(listPortInfo.at(i).portName());
    }
    return listComName;
}

void MainWindow::on_pushButton_clicked()
{
    static bool flagSerOpened = false;

    if(!flagSerOpened){
        //设置端口名
        QString portName;
        portName = ui->comboBox->currentText();
        serPort->setPortName(portName);
        //设置波特率
        qint32 baudRate = ui->comboBox_3->currentText().toInt();
        serPort->setBaudRate(baudRate);
        //设置数据位
        qint32 dataBits = ui->comboBox_2->currentText().toInt();
        switch (dataBits) {
        case 5:
            serPort->setDataBits(QSerialPort::Data5);
            break;
        case 6:
            serPort->setDataBits(QSerialPort::Data6);
            break;
        case 7:
            serPort->setDataBits(QSerialPort::Data7);
            break;
        case 8:
            serPort->setDataBits(QSerialPort::Data8);
            break;
        default:
            serPort->setDataBits(QSerialPort::UnknownDataBits);
            break;
        }

        //设置终止位
        QString stopBits = ui->comboBox_4->currentText();

        if(stopBits=="1"){
            serPort->setStopBits(QSerialPort::OneStop);
        }
        else if(stopBits=="1.5"){
            serPort->setStopBits(QSerialPort::OneAndHalfStop);
        }
        else if(stopBits=="2"){
            serPort->setStopBits(QSerialPort::TwoStop);
        }
        else{
            serPort->setStopBits(QSerialPort::UnknownStopBits);
        }

        //设置效验位
        QString parity = ui->comboBox_5->currentText();

        if(parity=="NoParity"){
            serPort->setParity(QSerialPort::NoParity);
        }
        else if(parity=="EvenParity"){
            serPort->setParity(QSerialPort::EvenParity);
        }
        else if(parity=="OddParity"){
            serPort->setParity(QSerialPort::OddParity);
        }
        else if(parity=="SpaceParity"){
            serPort->setParity(QSerialPort::SpaceParity);
        }
        else if(parity=="MarkParity"){
            serPort->setParity(QSerialPort::MarkParity);
        }
        else{
            serPort->setParity(QSerialPort::UnknownParity);
        }

        serPort->open(QSerialPort::ReadWrite);
        if(serPort->error()==QSerialPort::NoError){
            ui->label_12->setStyleSheet("background-image: url(:/img/light_open.png);");
            ui->pushButton->setText("关闭");
            flagSerOpened = true;
            qDebug("serport: open");

        }

    }
    else{
        serPort->close();
        ui->label_12->setStyleSheet("background-image: url(:/img/light.png);");
        ui->pushButton->setText("开启");
        flagSerOpened = false;
        qDebug("serport: close");
    }


}

void MainWindow::readSerPort()
{
    QByteArray data;
    data = serPort->readAll();

    int tempLen = ui->label_11->text().toInt();
    tempLen += data.length();
    ui->label_11->setText(QString::number(tempLen, 10));

    QByteArray buffData;
    QString strdata;
    bool flagHexChecked = ui->checkBox_2->isChecked();

    QString code;
    code = ui->comboBox_7->currentText();
    qDebug() << "code" << code;
    if(code == "UTF-8"){
        strdata = QString::fromUtf8(data);
    }

    if(flagHexChecked){
        buffData = data.toHex().toUpper();
        for(int i=2;i<buffData.length();i+=3){
            buffData.insert(i, " ");
        }
        strdata = QString::fromUtf8(buffData.data(), buffData.length());
    }
    else{
        strdata = QString::fromUtf8(data.data(), data.length());
    }


    bool flagColor = ui->checkBox_3->isChecked();
    if(flagColor&&flagColorCout){
        ui->textEdit->setTextBackgroundColor("#7ec242");
        flagColorCout = false;
    }
    else if(flagColor){
        ui->textEdit->setTextBackgroundColor("#758dc0");
        flagColorCout = true;
    }
    else{
        ui->textEdit->setTextBackgroundColor("#ffffff");
    }

    bool flagChecked = ui->checkBox->isChecked();
    if(flagChecked){
        QString _time;
        _time =  QTime::currentTime().toString("hh:mm:ss:zzz ");
        ui->textEdit->setTextColor("red");
        ui->textEdit->insertPlainText("["+_time+"] ");
        ui->textEdit->setTextColor("black");
        ui->textEdit->insertPlainText(strdata+"\n");
        ui->textEdit->moveCursor(QTextCursor::End);
    }
    else{
        ui->textEdit->insertPlainText(strdata);
        ui->textEdit->moveCursor(QTextCursor::End);
    }


}




void MainWindow::on_pushButton_2_clicked()
{
    QString strData;
    const char* sendData;
    QByteArray data;
    strData = ui->textEdit_1->toPlainText();

    QString code;
    code = ui->comboBox_6->currentText();
    if(code == "UTF-8"){
        data = strData.toUtf8();
    }

    bool flagChecked = ui->checkBox_6->isChecked();
    bool flagHexChecked =ui->checkBox_5->isChecked();
    if(flagHexChecked){
        data = data.toHex().toUpper();
    }

    if(flagChecked){
        data.append("\r\n");
    }
    sendData = data.data();
    serPort->write(sendData, strlen(sendData));
    int tempLen = ui->label_8->text().toInt();
    tempLen += strlen(sendData);
    ui->label_8->setText(QString::number(tempLen, 10));

}

void MainWindow::on_pushButton_5_clicked()
{
    ui->textEdit_1->clear();
}

void MainWindow::on_pushButton_4_clicked()
{
    ui->textEdit->clear();
}

int MainWindow::on_pushButton_3_clicked()
{
    QString data;
    data = ui->textEdit->toPlainText();

    // 弹出另存为对话框
    QString saveFilePath = QFileDialog::getSaveFileName(this, "Save Text File As", "", "Text Files (*.txt)");
    if (saveFilePath.isNull()) {
        return 0;
    }

    // 写入文件内容
    QFile outputFile(saveFilePath);
    if (!outputFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QMessageBox::critical(this, "Error", "Failed to save file!");
        return -1;
    }
    QTextStream out(&outputFile);
    out << data;
    outputFile.close();
    return 0;

}

void MainWindow::on_checkBox_4_clicked()
{
    bool flagAutoSend = ui->checkBox_4->isChecked();
    int delay = ui->lineEdit->text().toInt();
    if(flagAutoSend){
        timer->start(delay);
        qDebug() << "timer start: " << delay;
    }
    else {
        timer->stop();
    }

}

void MainWindow::on_pushButton_7_clicked()
{
    QString strData;
    const char* sendData;
    QByteArray data;
    strData = ui->textEdit_2->toPlainText();

    data = strData.toUtf8();


    bool flagChecked = ui->checkBox_6->isChecked();
    bool flagHexChecked =ui->checkBox_5->isChecked();
    if(flagHexChecked){
        data = data.toHex().toUpper();
    }

    if(flagChecked){
        data.append("\r\n");
    }
    sendData = data.data();
    serPort->write(sendData, strlen(sendData));
    int tempLen = ui->label_8->text().toInt();
    tempLen += strlen(sendData);
    ui->label_8->setText(QString::number(tempLen, 10));
}

void MainWindow::on_pushButton_8_clicked()
{
    QString strData;
    const char* sendData;
    QByteArray data;
    strData = ui->textEdit_3->toPlainText();

    data = strData.toUtf8();


    bool flagChecked = ui->checkBox_6->isChecked();
    bool flagHexChecked =ui->checkBox_5->isChecked();
    if(flagHexChecked){
        data = data.toHex().toUpper();
    }

    if(flagChecked){
        data.append("\r\n");
    }
    sendData = data.data();
    serPort->write(sendData, strlen(sendData));
    int tempLen = ui->label_8->text().toInt();
    tempLen += strlen(sendData);
    ui->label_8->setText(QString::number(tempLen, 10));
}

void MainWindow::on_pushButton_9_clicked()
{
    QString strData;
    const char* sendData;
    QByteArray data;
    strData = ui->textEdit_4->toPlainText();

    data = strData.toUtf8();


    bool flagChecked = ui->checkBox_6->isChecked();
    bool flagHexChecked =ui->checkBox_5->isChecked();
    if(flagHexChecked){
        data = data.toHex().toUpper();
    }

    if(flagChecked){
        data.append("\r\n");
    }
    sendData = data.data();
    serPort->write(sendData, strlen(sendData));
    int tempLen = ui->label_8->text().toInt();
    tempLen += strlen(sendData);
    ui->label_8->setText(QString::number(tempLen, 10));
}

void MainWindow::on_pushButton_10_clicked()
{
    QString strData;
    const char* sendData;
    QByteArray data;
    strData = ui->textEdit_5->toPlainText();

    data = strData.toUtf8();


    bool flagChecked = ui->checkBox_6->isChecked();
    bool flagHexChecked =ui->checkBox_5->isChecked();
    if(flagHexChecked){
        data = data.toHex().toUpper();
    }

    if(flagChecked){
        data.append("\r\n");
    }
    sendData = data.data();
    serPort->write(sendData, strlen(sendData));
    int tempLen = ui->label_8->text().toInt();
    tempLen += strlen(sendData);
    ui->label_8->setText(QString::number(tempLen, 10));
}

void MainWindow::on_commandLinkButton_clicked()
{
    QDesktopServices::openUrl(QUrl("https://gitee.com/bklooo/SerCom", QUrl::TolerantMode));
}
